<template>
  <div class="order-detail-page">
    <div class="container">
      <!-- 页面头部 -->
      <div class="page-header">
        <el-button @click="handleBack" :icon="ArrowLeft" circle />
        <h1>订单详情</h1>
        <div class="placeholder"></div>
      </div>

      <!-- 订单状态 -->
      <el-card class="status-card" v-if="orderInfo">
        <div class="status-content">
          <div class="status-icon">
            <el-icon :size="48" :color="getStatusColor(orderInfo.status)">
              <component :is="getStatusIcon(orderInfo.status)" />
            </el-icon>
          </div>
          <div class="status-info">
            <h2>{{ getStatusText(orderInfo.status) }}</h2>
            <p>{{ getStatusDesc(orderInfo.status) }}</p>
          </div>
          <div class="order-actions" v-if="hasActions">
            <el-button 
              v-if="canPay"
              type="primary"
              size="small"
              @click="payOrder"
            >
              立即支付
            </el-button>
            <el-button 
              v-if="canCancel"
              size="small"
              @click="cancelOrder"
            >
              取消订单
            </el-button>
          </div>
        </div>
      </el-card>

      <!-- 服务进度 -->
      <el-card class="progress-card" v-if="orderInfo && showProgress">
        <template #header>
          <div class="progress-header">
            <h3>服务进度</h3>
            <el-button 
              type="primary" 
              link 
              @click="viewProgress"
              size="small"
            >
              查看详情
            </el-button>
          </div>
        </template>
        
        <el-steps 
          :active="progressStep" 
          finish-status="success"
          class="order-steps"
        >
          <el-step title="订单确认" description="商家已接单" />
          <el-step title="准备服务" description="正在准备" />
          <el-step title="开始服务" description="服务进行中" />
          <el-step title="服务完成" description="等待评价" />
        </el-steps>
      </el-card>

      <!-- 订单基本信息 -->
      <el-card class="order-info-card" v-if="orderInfo">
        <template #header>
          <h3>订单信息</h3>
        </template>
        
        <div class="order-basic-info">
          <div class="info-row">
            <span class="label">订单号：</span>
            <span class="value">{{ orderInfo.orderNumber }}</span>
            <el-button 
              type="primary" 
              link 
              size="small"
              @click="copyOrderNumber"
            >
              复制
            </el-button>
          </div>
          
          <div class="info-row">
            <span class="label">下单时间：</span>
            <span class="value">{{ formatDateTime(orderInfo.createdAt) }}</span>
          </div>
          
          <div class="info-row" v-if="orderInfo.paidAt">
            <span class="label">支付时间：</span>
            <span class="value">{{ formatDateTime(orderInfo.paidAt) }}</span>
          </div>
          
          <div class="info-row" v-if="orderInfo.completedAt">
            <span class="label">完成时间：</span>
            <span class="value">{{ formatDateTime(orderInfo.completedAt) }}</span>
          </div>
        </div>
      </el-card>

      <!-- 服务详情 -->
      <el-card class="service-detail-card" v-if="orderInfo">
        <template #header>
          <h3>服务详情</h3>
        </template>
        
        <div class="service-content">
          <div class="service-main">
            <div class="service-image">
              <el-image
                :src="orderInfo.service?.image || '/default-service.jpg'"
                fit="cover"
                class="image"
              />
            </div>
            <div class="service-details">
              <h4>{{ orderInfo.service?.name }}</h4>
              <p class="merchant-name">{{ orderInfo.merchant?.name }}</p>
              <div class="service-meta">
                <span>¥{{ orderInfo.service?.price }}/{{ orderInfo.service?.unit }}</span>
                <span>×{{ orderInfo.quantity }}</span>
              </div>
            </div>
          </div>
          
          <div class="service-extra">
            <div class="extra-item" v-if="orderInfo.appointmentDate">
              <span class="extra-label">预约时间：</span>
              <span class="extra-value">
                {{ formatDate(orderInfo.appointmentDate) }} {{ orderInfo.appointmentTime }}
              </span>
            </div>
            
            <div class="extra-item" v-if="orderInfo.note">
              <span class="extra-label">备注信息：</span>
              <span class="extra-value">{{ orderInfo.note }}</span>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 地址信息 -->
      <el-card class="address-card" v-if="orderInfo?.address">
        <template #header>
          <h3>服务地址</h3>
        </template>
        
        <div class="address-content">
          <div class="address-info">
            <div class="address-main">
              <el-icon class="location-icon"><LocationFilled /></el-icon>
              <div class="address-details">
                <p class="address-text">{{ orderInfo.address.fullAddress }}</p>
                <p class="contact-info">
                  {{ orderInfo.address.contactName }} {{ orderInfo.address.contactPhone }}
                </p>
              </div>
            </div>
            <el-button 
              type="primary" 
              link 
              @click="viewLocation"
              size="small"
            >
              查看位置
            </el-button>
          </div>
        </div>
      </el-card>

      <!-- 费用明细 -->
      <el-card class="payment-card">
        <template #header>
          <h3>费用明细</h3>
        </template>
        
        <div class="payment-details">
          <div class="payment-item">
            <span class="payment-label">服务费用</span>
            <span class="payment-value">¥{{ orderInfo?.serviceFee || 0 }}</span>
          </div>
          
          <div class="payment-item" v-if="orderInfo?.deliveryFee">
            <span class="payment-label">配送费用</span>
            <span class="payment-value">¥{{ orderInfo.deliveryFee }}</span>
          </div>
          
          <div class="payment-item" v-if="orderInfo?.discountAmount">
            <span class="payment-label">优惠金额</span>
            <span class="payment-value discount">-¥{{ orderInfo.discountAmount }}</span>
          </div>
          
          <div class="payment-item total">
            <span class="payment-label">实付金额</span>
            <span class="payment-value">¥{{ orderInfo?.totalAmount || 0 }}</span>
          </div>
          
          <div class="payment-method" v-if="orderInfo?.paymentMethod">
            <span class="payment-label">支付方式</span>
            <span class="payment-value">{{ getPaymentMethodText(orderInfo.paymentMethod) }}</span>
          </div>
        </div>
      </el-card>

      <!-- 商家信息 -->
      <el-card class="merchant-card" v-if="orderInfo?.merchant">
        <template #header>
          <h3>商家信息</h3>
        </template>
        
        <div class="merchant-content">
          <div class="merchant-info">
            <div class="merchant-avatar">
              <el-image
                :src="orderInfo.merchant.avatar || '/default-merchant.jpg'"
                fit="cover"
                class="avatar"
              />
            </div>
            <div class="merchant-details">
              <h4>{{ orderInfo.merchant.name }}</h4>
              <p class="merchant-desc">{{ orderInfo.merchant.description || '专业洗护服务' }}</p>
              <div class="merchant-rating" v-if="orderInfo.merchant.rating">
                <el-rate 
                  :model-value="orderInfo.merchant.rating" 
                  disabled 
                  size="small"
                />
                <span class="rating-text">{{ orderInfo.merchant.rating }}</span>
              </div>
            </div>
          </div>
          
          <div class="merchant-actions">
            <el-button 
              @click="viewMerchant"
              :icon="Shop"
              size="small"
            >
              进店看看
            </el-button>
            <el-button 
              @click="contactMerchant"
              :icon="ChatDotRound"
              size="small"
            >
              联系商家
            </el-button>
          </div>
        </div>
      </el-card>

      <!-- 操作按钮 -->
      <div class="action-buttons" v-if="orderInfo">
        <el-button 
          v-if="canViewProgress"
          type="primary"
          size="large"
          @click="viewProgress"
          :icon="View"
        >
          查看进度
        </el-button>
        
        <el-button 
          v-if="canRate"
          type="primary"
          size="large"
          @click="rateOrder"
          :icon="Star"
        >
          评价服务
        </el-button>
        
        <el-button 
          v-if="canReorder"
          size="large"
          @click="reorder"
          :icon="Refresh"
        >
          再次下单
        </el-button>
        
        <el-button 
          v-if="canRefund"
          size="large"
          @click="requestRefund"
          :icon="RefundFilled"
        >
          申请退款
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft,
  LocationFilled,
  Shop,
  ChatDotRound,
  View,
  Star,
  Refresh,
  RefundFilled,
  Clock,
  Checked,
  Loading,
  CircleCloseFilled,
  WarningFilled
} from '@element-plus/icons-vue'
import { orderApi } from '@/services/api'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()

// 数据定义
const orderInfo = ref(null)
const loading = ref(true)

// 计算属性
const progressStep = computed(() => {
  if (!orderInfo.value) return 0
  
  const statusMap = {
    pending: 0,
    paid: 1,
    confirmed: 1,
    in_service: 2,
    completed: 3,
    cancelled: 0
  }
  
  return statusMap[orderInfo.value.status] || 0
})

const showProgress = computed(() => {
  return orderInfo.value && ['paid', 'confirmed', 'in_service', 'completed'].includes(orderInfo.value.status)
})

const hasActions = computed(() => {
  return canPay.value || canCancel.value
})

const canPay = computed(() => {
  return orderInfo.value && orderInfo.value.status === 'pending'
})

const canCancel = computed(() => {
  return orderInfo.value && ['pending', 'paid', 'confirmed'].includes(orderInfo.value.status)
})

const canViewProgress = computed(() => {
  return orderInfo.value && ['confirmed', 'in_service'].includes(orderInfo.value.status)
})

const canRate = computed(() => {
  return orderInfo.value && orderInfo.value.status === 'completed' && !orderInfo.value.isRated
})

const canReorder = computed(() => {
  return orderInfo.value && ['completed', 'cancelled'].includes(orderInfo.value.status)
})

const canRefund = computed(() => {
  return orderInfo.value && ['paid', 'confirmed'].includes(orderInfo.value.status)
})

// 生命周期
onMounted(() => {
  const orderId = route.params.id
  if (orderId) {
    fetchOrderDetail(orderId)
  }
})

// 方法定义
const fetchOrderDetail = async (orderId) => {
  try {
    loading.value = true
    const response = await orderApi.getOrderDetail(orderId)
    orderInfo.value = response.data
  } catch (error) {
    console.error('获取订单详情失败:', error)
    
    // 使用模拟数据
    const mockOrderId = parseInt(orderId)
    orderInfo.value = {
      id: mockOrderId,
      orderNumber: `202412280${mockOrderId.toString().padStart(3, '0')}`,
      status: 'completed',
      createdAt: new Date(Date.now() - 86400000),
      paidAt: new Date(Date.now() - 86000000),
      completedAt: new Date(Date.now() - 3600000),
      appointmentDate: '2024-12-29',
      appointmentTime: '14:00-15:00',
      quantity: 2,
      serviceFee: 70,
      deliveryFee: 0,
      discountAmount: 5,
      totalAmount: 65,
      paymentMethod: 'wechat',
      note: '请小心处理',
      isRated: false,
      merchant: {
        id: 1,
        name: '专业洗护店',
        description: '专业提供高端洗护服务',
        avatar: '/default-merchant.jpg',
        rating: 4.8
      },
      service: {
        id: 1,
        name: '高档衣物干洗',
        price: 35,
        unit: '件',
        image: '/default-service.jpg'
      },
      address: {
        fullAddress: '北京市朝阳区三里屯SOHO 1号楼1001室',
        contactName: '张三',
        contactPhone: '138****1234'
      }
    }
    
    ElMessage.error('获取订单详情失败，显示模拟数据')
  } finally {
    loading.value = false
  }
}

const handleBack = () => {
  router.back()
}

const payOrder = () => {
  if (orderInfo.value) {
    router.push(`/payment/${orderInfo.value.id}`)
  }
}

const cancelOrder = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要取消该订单吗？取消后无法恢复。',
      '取消订单',
      {
        confirmButtonText: '确定取消',
        cancelButtonText: '我再想想',
        type: 'warning'
      }
    )

    await orderApi.cancelOrder(orderInfo.value.id)
    
    ElMessage.success('订单已取消')
    
    // 刷新订单信息
    fetchOrderDetail(orderInfo.value.id)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
    }
  }
}

const viewProgress = () => {
  if (orderInfo.value) {
    router.push(`/orders/${orderInfo.value.id}/progress`)
  }
}

const rateOrder = () => {
  if (orderInfo.value) {
    router.push(`/orders/${orderInfo.value.id}/rating`)
  }
}

const reorder = () => {
  if (orderInfo.value) {
    router.push(`/services/${orderInfo.value.service.id}`)
  }
}

const requestRefund = () => {
  ElMessage.info('退款功能开发中')
}

const copyOrderNumber = async () => {
  try {
    await navigator.clipboard.writeText(orderInfo.value.orderNumber)
    ElMessage.success('订单号已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

const viewLocation = () => {
  ElMessage.info('地图功能开发中')
}

const viewMerchant = () => {
  if (orderInfo.value?.merchant) {
    router.push(`/merchants/${orderInfo.value.merchant.id}`)
  }
}

const contactMerchant = () => {
  if (orderInfo.value?.merchant) {
    router.push(`/chat/${orderInfo.value.merchant.id}?orderId=${orderInfo.value.id}`)
  }
}

const getStatusIcon = (status) => {
  const iconMap = {
    pending: Clock,
    paid: Checked,
    confirmed: Checked,
    in_service: Loading,
    completed: Checked,
    cancelled: CircleCloseFilled,
    failed: WarningFilled
  }
  return iconMap[status] || Clock
}

const getStatusColor = (status) => {
  const colorMap = {
    pending: '#e6a23c',
    paid: '#409eff',
    confirmed: '#409eff',
    in_service: '#409eff',
    completed: '#67c23a',
    cancelled: '#909399',
    failed: '#f56c6c'
  }
  return colorMap[status] || '#909399'
}

const getStatusText = (status) => {
  const textMap = {
    pending: '待支付',
    paid: '已支付',
    confirmed: '商家已接单',
    in_service: '服务进行中',
    completed: '服务已完成',
    cancelled: '订单已取消',
    failed: '订单失败'
  }
  return textMap[status] || '未知状态'
}

const getStatusDesc = (status) => {
  const descMap = {
    pending: '请在30分钟内完成支付',
    paid: '商家将尽快确认订单',
    confirmed: '商家正在准备服务',
    in_service: '服务人员正在为您提供服务',
    completed: '感谢您的使用，记得评价哦',
    cancelled: '订单已被取消',
    failed: '订单处理失败，请联系客服'
  }
  return descMap[status] || ''
}

const getPaymentMethodText = (method) => {
  const methodMap = {
    wechat: '微信支付',
    alipay: '支付宝',
    unionpay: '银联支付',
    balance: '余额支付'
  }
  return methodMap[method] || '其他'
}

const formatDate = (date) => {
  return dayjs(date).format('MM-DD')
}

const formatDateTime = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm')
}
</script>

<style lang="scss" scoped>
.order-detail-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px 0;
}

.container {
  max-width: 600px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  h1 {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
    color: #333;
  }

  .placeholder {
    width: 32px;
  }
}

.el-card {
  margin-bottom: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  .el-card__header {
    padding: 16px 20px;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }

    .progress-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }

  .el-card__body {
    padding: 20px;
  }
}

.status-card {
  .status-content {
    display: flex;
    align-items: center;
    gap: 16px;

    .status-info {
      flex: 1;

      h2 {
        margin: 0 0 4px 0;
        font-size: 20px;
        color: #333;
      }

      p {
        margin: 0;
        color: #666;
        font-size: 14px;
      }
    }

    .order-actions {
      display: flex;
      flex-direction: column;
      gap: 8px;
    }
  }
}

.progress-card {
  .order-steps {
    margin: 20px 0;

    :deep(.el-step__description) {
      color: #666;
      font-size: 12px;
    }
  }
}

.order-info-card {
  .order-basic-info {
    .info-row {
      display: flex;
      align-items: center;
      margin-bottom: 12px;
      gap: 8px;

      .label {
        color: #666;
        font-size: 14px;
        min-width: 80px;
      }

      .value {
        color: #333;
        font-size: 14px;
        flex: 1;
      }
    }
  }
}

.service-detail-card {
  .service-content {
    .service-main {
      display: flex;
      gap: 12px;
      margin-bottom: 16px;

      .service-image {
        width: 60px;
        height: 60px;
        border-radius: 8px;
        overflow: hidden;
        flex-shrink: 0;

        .image {
          width: 100%;
          height: 100%;
        }
      }

      .service-details {
        flex: 1;

        h4 {
          margin: 0 0 4px 0;
          font-size: 16px;
          color: #333;
        }

        .merchant-name {
          margin: 0 0 8px 0;
          color: #666;
          font-size: 14px;
        }

        .service-meta {
          display: flex;
          gap: 8px;
          font-size: 12px;
          color: #999;
        }
      }
    }

    .service-extra {
      border-top: 1px solid #f0f0f0;
      padding-top: 16px;

      .extra-item {
        display: flex;
        margin-bottom: 8px;

        .extra-label {
          color: #666;
          font-size: 14px;
          min-width: 80px;
        }

        .extra-value {
          color: #333;
          font-size: 14px;
          flex: 1;
        }
      }
    }
  }
}

.address-card {
  .address-content {
    .address-info {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;

      .address-main {
        display: flex;
        gap: 12px;
        flex: 1;

        .location-icon {
          color: #409eff;
          margin-top: 2px;
          flex-shrink: 0;
        }

        .address-details {
          flex: 1;

          .address-text {
            margin: 0 0 4px 0;
            color: #333;
            font-size: 14px;
            line-height: 1.4;
          }

          .contact-info {
            margin: 0;
            color: #666;
            font-size: 12px;
          }
        }
      }
    }
  }
}

.payment-card {
  .payment-details {
    .payment-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;

      .payment-label {
        color: #666;
        font-size: 14px;
      }

      .payment-value {
        color: #333;
        font-size: 14px;

        &.discount {
          color: #67c23a;
        }
      }

      &.total {
        border-top: 1px solid #f0f0f0;
        padding-top: 12px;
        margin-top: 8px;

        .payment-label,
        .payment-value {
          font-weight: 600;
          font-size: 16px;
          color: #e6a23c;
        }
      }
    }

    .payment-method {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 8px;
      padding-top: 8px;
      border-top: 1px solid #f0f0f0;

      .payment-label {
        color: #666;
        font-size: 14px;
      }

      .payment-value {
        color: #333;
        font-size: 14px;
      }
    }
  }
}

.merchant-card {
  .merchant-content {
    .merchant-info {
      display: flex;
      gap: 12px;
      margin-bottom: 16px;

      .merchant-avatar {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        overflow: hidden;
        flex-shrink: 0;

        .avatar {
          width: 100%;
          height: 100%;
        }
      }

      .merchant-details {
        flex: 1;

        h4 {
          margin: 0 0 4px 0;
          font-size: 16px;
          color: #333;
        }

        .merchant-desc {
          margin: 0 0 8px 0;
          color: #666;
          font-size: 12px;
        }

        .merchant-rating {
          display: flex;
          align-items: center;
          gap: 8px;

          .rating-text {
            color: #e6a23c;
            font-size: 12px;
            font-weight: 500;
          }
        }
      }
    }

    .merchant-actions {
      display: flex;
      gap: 12px;
    }
  }
}

.action-buttons {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
  margin-top: 24px;
  margin-bottom: 40px;

  .el-button {
    height: 48px;
    font-size: 16px;
  }
}

@media (max-width: 768px) {
  .container {
    padding: 0 10px;
  }

  .status-content {
    flex-direction: column;
    text-align: center;

    .order-actions {
      flex-direction: row;
      width: 100%;
    }
  }

  .service-main {
    flex-direction: column;
    text-align: center;

    .service-image {
      align-self: center;
    }
  }

  .address-info {
    flex-direction: column;
    gap: 12px;
  }

  .merchant-actions {
    justify-content: center;
  }

  .action-buttons {
    grid-template-columns: 1fr;
    gap: 16px;
  }
}
</style> 